package com.hm.health.Utils;

import android.content.Context;

import com.goodix.libromablecom.sdk.cardiff.CardiffOtaUpdate;

import java.io.File;

import rx.Observable;
import rx.Subscriber;

public class FirmwareOtaUpdateSubscribe implements Observable.OnSubscribe<Integer>{

    private Context mContext;
    private String mFirmarePath;
    private CardiffOtaUpdate cardiffOtaUpdate;

    public FirmwareOtaUpdateSubscribe(Context context, String firmarePath) {
        mContext = context;
        mFirmarePath = firmarePath;
    }

    @Override
    public void call(Subscriber<? super Integer> subscriber) {
        File file = new File(mFirmarePath);
        if (!file.exists()) {
            subscriber.onError(new Throwable("Firmware does not exist, please download firmware again"));
            return;
        }

        cardiffOtaUpdate = new CardiffOtaUpdate(mContext, new CardiffOtaUpdate.Listener() {
            @Override
            public void errorBeforeUpdating(String msg) {
                subscriber.onError(new Throwable(msg));
                cardiffOtaUpdate.deinit();
            }

            @Override
            public void debugLog(String msg) {

            }

            @Override
            public void log(String msg) {

            }

            @Override
            public void setProgress(int progress) {
                subscriber.onNext(progress);
            }

            @Override
            public void onSuccess() {
                cardiffOtaUpdate.deinit();
                subscriber.onCompleted();
            }

            @Override
            public void onFailure() {
                cardiffOtaUpdate.deinit();
                subscriber.onError(new Throwable("Upgrade failed"));
            }

            @Override
            public void onUpdating() {

            }
        });
        cardiffOtaUpdate.update(file);
    }
}
